package com.digitalchina.lxnsy.activity.old;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessTraining;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.TrainVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hedgehog.ratingbar.RatingBar;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2017/3/24 17:59
 * 修改备注：
 * ================================================
 */

public class AgriculturalTrainingDetailsActivity extends BaseActivity {


    @Bind(R.id.train_details_tv_title)
    TextView trainDetailsTvTitle;
    @Bind(R.id.headview_lecturer_tv_score_tip)
    TextView headviewLecturerTvScoreTip;
    @Bind(R.id.train_details_rb_score)
    RatingBar trainDetailsRbScore;
    @Bind(R.id.train_details_tv_expert_name)
    TextView trainDetailsTvExpertName;
    @Bind(R.id.train_details_tv_show_expert_name)
    TextView trainDetailsTvShowExpertName;
    @Bind(R.id.train_details_tv_expert_title)
    TextView trainDetailsTvExpertTitle;
    @Bind(R.id.train_details_tv_show_expert_title)
    TextView trainDetailsTvShowExpertTitle;
    @Bind(R.id.train_details_tv_expert_field)
    TextView trainDetailsTvExpertField;
    @Bind(R.id.train_details_tv_show_expert_field)
    TextView trainDetailsTvShowExpertField;
    @Bind(R.id.train_details_sdv_expert_avatar)
    SimpleDraweeView trainDetailsSdvExpertAvatar;
    @Bind(R.id.train_details_tv_attend)
    TextView trainDetailsTvAttend;
    @Bind(R.id.train_details_sdv_expert_avatar_follow)
    RelativeLayout trainDetailsSdvExpertAvatarFollow;
    @Bind(R.id.train_details_tv_expert_intro)
    TextView trainDetailsTvExpertIntro;
    @Bind(R.id.train_details_tv_show_expert_intro)
    TextView trainDetailsTvShowExpertIntro;
    @Bind(R.id.train_details_tv_train_intro)
    TextView trainDetailsTvTrainIntro;
    @Bind(R.id.train_details_tv_show_train_intro)
    TextView trainDetailsTvShowTrainIntro;
    @Bind(R.id.train_details_tv_train_date)
    TextView trainDetailsTvTrainDate;
    @Bind(R.id.train_details_tv_show_train_date)
    TextView trainDetailsTvShowTrainDate;
    @Bind(R.id.train_details_tv_train_address)
    TextView trainDetailsTvTrainAddress;
    @Bind(R.id.train_details_tv_show_train_address)
    TextView trainDetailsTvShowTrainAddress;
    @Bind(R.id.bmapView)
    TextureMapView mMapView;
    @Bind(R.id.train_details_tv_show_work_place)
    TextView trainDetailsTvShowWorkPlace;
    @Bind(R.id.train_details_tv_show_expert_grade)
    TextView trainDetailsTvShowExpertGrade;

    private String teacherId = "";
    private TrainVO trainVO;
    private boolean isAttend = false;

    private BitmapDescriptor bd = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_gcoding); // 百度地图marker标识


    @Override
    public void setLayout() {
        setTitle("培训详情");
        setContentLayout(R.layout.activity_agricultural_training_details);
    }

    @Override
    public void initMember() {
        if (getIntent().hasExtra("JPush_attention")) { // 关注提醒(极光推送)
            String trainId = (String) getIntent().getSerializableExtra("JPush_attention");
            if (!StringUtil.isStrEmpty(trainId))
                BusinessTraining.getTrainDetail(this, trainId, mHandler);
        } else if (getIntent().hasExtra("toTrainDetails")) {
            trainVO = (TrainVO) getIntent().getSerializableExtra("toTrainDetails");
            if (null != trainVO) {
                initContent();
            }
        }
    }

    /**
     * 填充内容
     */
    private void initContent() {
        if (null != trainVO.getAgriTeacher()) {
            teacherId = trainVO.getAgriTeacher().getId();
            if (Utils.isLogin(this))
                BusinessTraining.attentionStatus(this, teacherId, "", mHandler);
            else
                changeAttendStatus();
        }

        FrescoUtil.showImageSmall(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getImg() == null ? "" : trainVO.getAgriTeacher().getImg(), trainDetailsSdvExpertAvatar);
        trainDetailsTvTitle.setText(trainVO.getTitle() == null ? "" : trainVO.getTitle()); // 标题
//        trainDetailsRbScore.setStar(trainVO.getScore());  // 评分
        trainDetailsTvShowExpertName.setText(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getName() == null ? "" : trainVO.getAgriTeacher().getName()); // 专家姓名
        trainDetailsTvShowExpertTitle.setText(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getTitle() == null ? "" : trainVO.getAgriTeacher().getTitle()); // 职务职称
        trainDetailsTvShowWorkPlace.setText(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getWorkUnit() == null ? "" : trainVO.getAgriTeacher().getWorkUnit()); // 工作单位
        trainDetailsTvShowExpertField.setText(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getProfession() == null ? "" : trainVO.getAgriTeacher().getProfession()); // 从事专业
        if (trainVO.getAgriTeacher() != null && !StringUtil.isStrEmpty(trainVO.getAgriTeacher().getTrainScore())) {
            if (Integer.parseInt(trainVO.getAgriTeacher().getTrainScore()) < 36)
                trainDetailsTvShowExpertGrade.setText("差");
            else if (Integer.parseInt(trainVO.getAgriTeacher().getTrainScore()) < 42)
                trainDetailsTvShowExpertGrade.setText("中");
            else if (Integer.parseInt(trainVO.getAgriTeacher().getTrainScore()) < 48)
                trainDetailsTvShowExpertGrade.setText("良");
            else if (Integer.parseInt(trainVO.getAgriTeacher().getTrainScore()) < 60)
                trainDetailsTvShowExpertGrade.setText("优");
        } else
            trainDetailsTvShowExpertGrade.setText("暂无"); // TODO 评分
//        trainDetailsTvShowExpertIntro.setText(trainVO.getAgriTeacher() == null ? "" : trainVO.getAgriTeacher().getSummary() == null ? "" : trainVO.getAgriTeacher().getSummary()); // 专家简介

        String trainingContents = "";
        if (trainVO.getTrainingContents() != null && trainVO.getTrainingContents().size() > 0) {
            for (int i = 0; i < trainVO.getTrainingContents().size(); i++) {
                if (i == trainVO.getTrainingContents().size() - 1)
                    trainingContents += trainVO.getTrainingContents().get(i).getContentType().getName() + "：" + trainVO.getTrainingContents().get(i).getContentDescribe();
                else
                    trainingContents += trainVO.getTrainingContents().get(i).getContentType().getName() + "：" + trainVO.getTrainingContents().get(i).getContentDescribe() + "\n";
            }
            trainDetailsTvShowTrainIntro.setText(trainingContents); // 培训内容
        } else
            trainDetailsTvShowTrainIntro.setText("暂无内容"); // 培训内容

        List<TrainVO.TrainingTimesBean> trainingTimesBeanList = trainVO.getTrainingTimes();
        if (null != trainingTimesBeanList && trainingTimesBeanList.size() > 0) { // 培训时间不为空
            for (int i = 0; i < trainingTimesBeanList.size(); i++) {
                if (i == trainingTimesBeanList.size() - 1) // 最后一条时间不换行
                    trainDetailsTvShowTrainDate.setText(String.format("%s", trainingTimesBeanList.get(i).getTrainDate() + " " + trainingTimesBeanList.get(i).getStartTime() + "-" + trainingTimesBeanList.get(i).getEndTime()));
                else
                    trainDetailsTvShowTrainDate.setText(String.format("%s%n", trainingTimesBeanList.get(i).getTrainDate() + " " + trainingTimesBeanList.get(i).getStartTime() + "-" + trainingTimesBeanList.get(i).getEndTime()));
            }
        }
        trainDetailsTvShowTrainAddress.setText(trainVO.getFullAddress() == null ? "" : trainVO.getFullAddress());

        if (!StringUtil.isStrEmpty(trainVO.getLatitude()) && !StringUtil.isStrEmpty(trainVO.getLongitude()))
            iniMapView(Double.parseDouble(trainVO.getLatitude()), Double.parseDouble(trainVO.getLongitude()));
    }

    /**
     * 更改关注按钮的状态
     */
    private void changeAttendStatus() {
        if (isAttend) { // 已关注
            trainDetailsSdvExpertAvatarFollow.setBackgroundResource(R.drawable.shape_already_attend);
            trainDetailsTvAttend.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.bd_ic_check_mark), null, null, null);
            trainDetailsTvAttend.setText("已关注");
            trainDetailsTvAttend.setTextColor(Color.parseColor("#B3B3B3"));
        } else {
            trainDetailsSdvExpertAvatarFollow.setBackgroundResource(R.drawable.shape_headview_lecturer_follow);
            trainDetailsTvAttend.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.icon_headview_lecturer_add_follows), null, null, null);
            trainDetailsTvAttend.setText("关注");
            trainDetailsTvAttend.setTextColor(getResources().getColor(R.color.app_color));
        }
    }

    /**
     * 设置地图信息
     */
    private void iniMapView(Double latitude, Double longitude) {
        mMapView.showZoomControls(false);
        //获取地图控件引用
        BaiduMap mBaiduMap = mMapView.getMap();
        UiSettings mUiSettings = mBaiduMap.getUiSettings();
        mUiSettings.setAllGesturesEnabled(false); // 是否禁用所有手势
        mUiSettings.setZoomGesturesEnabled(false);
        mUiSettings.setScrollGesturesEnabled(false);

        mBaiduMap.setMaxAndMinZoomLevel(21.0f, 19.0f);

        //108.875169,34.201621 西安神州数码有限公司
        //108.95346,34.265725 东西南北四条大街交汇处 钟楼
        //定义Maker坐标点
//        LatLng point = new LatLng(108.875169, 34.201621);
        LatLng point = new LatLng(latitude, longitude);
        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions option = new MarkerOptions()
                .position(point)
                .icon(bd)
                .zIndex(9);
        // 掉下动画
        option.animateType(MarkerOptions.MarkerAnimateType.drop);
        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);

        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(point);
        mBaiduMap.setMapStatus(mapStatusUpdate);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (null != mMapView)
            mMapView.onDestroy();
        bd.recycle();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (null != mMapView)
            mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (null != mMapView)
            mMapView.onPause();
    }

    @Override
    public void addListener() {
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                back();
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_TO_ADD_ATTENTION_SUCCESS: // 关注
                        if (isAttend) {
                            isAttend = false;
                            changeAttendStatus();
                        } else {
                            isAttend = true;
                            changeAttendStatus();
                        }
                        break;
                    case MSG.MSG_TO_ADD_ATTENTION_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_TRAIN_DETAIL_SUCCESS: // 培训详情
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_TRAIN_DETAIL_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_ATTENTION_STATUS_SUCCESS: // 是否被关注(isAttend为1 已关注)
                        String isAttendStr = FastJsonUtil.getString(msg.obj.toString(), "isAttend");
                        if (!StringUtil.isStrEmpty(isAttendStr) && isAttendStr.equals("1")) {
                            isAttend = true;
                            changeAttendStatus();
                        } else {
                            isAttend = false;
                            changeAttendStatus();
                        }
                        break;
                    case MSG.MSG_ATTENTION_STATUS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        trainVO = FastJsonUtil.getBean(object.toString(), "body", "agriTraining", TrainVO.class);
        initContent();
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.train_details_tv_attend)
    public void onClick() { // 关注
        if (Utils.isLogin(this)) {
            if (!StringUtil.isStrEmpty(teacherId))
                BusinessTraining.toAddAttention(this, teacherId, "", mHandler);
        } else
            Utils.notLoginGoto(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 返回
     */
    public void back() {
        Utils.finishActivity(AgriculturalTrainingDetailsActivity.this);
    }
}
